var wAdmin;
var messages = {};
(function (w ) {
// @clasname @boolean(true:show overwise hide)
//    w.fn.classItemLabasTago = function(clas, x){
//        if (x=== true)w(clas).show();
//        else w(clas).show();
//    };
    w.fn.wAdmin = function(options) {
        var s = w.extend({
            // These are the defaults.
            "pass_len":8// Minimum Password length
        }, options );
        
        var fields = [
               'store_name','account_name','email','password','lname','fname',
        ];
        var fields_combo = [
               'status','shr','smin','ehr','emin'
        ];
        var btnClick = false;
        
        var msgs = {
            "user_exist":"Username already exists"
            ,"pass_limit":"Password must be at least 8 characters."
            ,"pass_notmatched":"Password do not matched."
            ,"pass_required":"Username is a required field."
            ,"server_error":"Server error."
            ,"user_unlock":"User successfully unlocked."
            ,"invalid_password":"Invalid Password."
            
        };

        var m = {
            _init:function(){
            },
            numeric:function(evt){
                evt = evt || window.event;
                var charCode = evt.which || evt.keyCode;
                var charStr = String.fromCharCode(charCode);
//                if ( /[a-z0-9]/i.test(charStr) || evt.which == 8 || evt.which == 9 || (evt.which > 36 || evt.which < 41)) {
//                }else{
//                    return false;
//                }
                // 48-57(0-9);  65-89(A-Z); 97-122(a-z)
                if (evt.which !== 8 && evt.which !== 0 && (evt.which < 48 || evt.which > 57)) {
                    return false;
                }
            },
            resizeFrame:function(){
        
                if (window.self === window.top){
                    // Its NOT an iframe load base.
                    return; // Skip resizing the frame
                }
                console.log("resizeFrame");
                window.postMessage(document.body.scrollHeight,"*");

                w(window).resize( function () {                    
                    console.log("onload resize-" + document.body.scrollHeight);
                    var height = document.body.scrollHeight;

                    if ("window", w(window).width() ===  1024){
                        //do nothing
                    }else {
                        if (/gallery/.test(self.location.href)){ 
                            var hgt = w("div.category-products").height();
                            if (hgt > 370){
                                //console.log("onload if " + height);
                                window.parent.postMessage(parseInt(height),"*");
                            }
                        } else { //console.log("onload else " + height);
                            if(("window", w(window).width() === 480) && (/iPhone/.test(navigator.userAgent)) && (/specification/.test(self.location.href))){
                                height = 1965;
                            }
                            window.parent.postMessage(parseInt(height),"*");
                        }
                    }

                }).resize();	// on change

                w('html,body').bind('heightChange', function(){ });
            },
            isEmtpy: function(elem){
                if (w.trim(elem.val()).length === 0) {
                    elem.addClass("error");
                    return true;
                } else {
                    elem.removeClass("error");
                    return false;
                }
                
            },// isEmtpy
            isEmtpyClassic: function(elem){
                if (w.trim(elem.val()).length === 0) {
                    elem.addClass("error-input");
                    return true;
                } else {
                    elem.removeClass("error-input");
                    return false;
                }
                
            }, // isEmtpyClassic
            isValidPassword:function(elem){
                var passlen = w.trim(elem.val()).length;
                // If password length greaten than zero. assume that new user.
                // If password is empty, I will assume she only she only updating some user info.
                if ((passlen>0) && !((passlen >=s.pass_len) && (passlen<=30))) {
                    return false;
                }
                return true;
            },
            /** ------------------------------
            * Validate email	
            * DHTML email validation script. Courtesy of SmartWebby.com (http://www.smartwebby.com/dhtml/)
            * @param str email
            / -----------------------------*/
            isValidEmail:function (email) {
                var at="@";
                var dot=".";
                var lat=email.indexOf(at);
                var lstr=email.length;
                //var ldot=email.indexOf(dot);
                if (email.indexOf(at)=== -1){
                    return false;
                }

                if ((email.indexOf(at)===-1) || (email.indexOf(at)===0) || (email.indexOf(at)===lstr)){
                    return false;
                }

                if ((email.indexOf(dot)===-1) || (email.indexOf(dot)===0) || (email.indexOf(dot)===lstr)){
                    return false;
                }

                if ((email.indexOf(at,(lat+1))!==-1)){
                    return true;
                }

                if ((email.substring(lat-1,lat)===dot) || (email.substring(lat+1,lat+2)===dot)){
                   return false; 
                }

                if (email.indexOf(dot,(lat+2))===-1){
                   return false;
                }

                if (email.indexOf(" ")!==-1){
                    return false;
                }

                return true;

            },
            getCookie:function (cname) {
                var name = cname + "=";
                var ca = document.cookie.split(';');
                for(var i=0; i<ca.length; i++){
                    var c = ca[i].replace(/\s/g, "");
                    if (c.indexOf(name)===0) return c.substring(name.length,c.length);
                }
                return "";
            },
            /**
             * @param str data
             */
            urlencode:function (data) {
                return encodeURIComponent(data).replace(/'/g,"%27").replace(/"/g,"%22");	
            },
            urldecode: function (data) {
                return decodeURIComponent(data.replace(/\+/g,  " "));
            },
            hideError:function(elem){
                if (undefined != elem){
                    elem.hide();
                }else{
                    w('#admin-error').hide();
                }
            }
        }; // End Methods

        // Input filtering
        w("#frm_pricerange input[type=text]").keypress(function(event){
            return m.numeric(event);
        });
        
        
        /** ===============================================================
         *                 START
         *  Form Validation Section Code
         ================================================================== */
//        w("#frm_pricerange").submit(function(evt){
//            // For Deletion na to.
//            var min = w("#frm_pricerange input[name=min]");
//            var max = w("#frm_pricerange input[name=max]");
//            if (m.isEmtpy(min) || m.isEmtpy(max)){
//                alert("Please input valid data.");
//            }else{
//                if (parseInt(min.val()) > parseInt(max.val())){
//                    //alert("Please validate your data.");
//                }else{
//                    //alert(min.val()+" > "+max.val());
//                    return true;
//                }
//            }
//            return false;
//        });
        
        /** -----------------------------------------
         * 
         */
        w("#frm_resetpass").submit(function(evt){
            w('#error-msg').hide();
            //if (w.trim(w('input[name=account_name]').val()).length < 5){                
            var accntName = w('input[name=account_name]');
            if (m.isEmtpy(accntName)){
                accntName.focus();
                w('#account_name').show().html(msgs.user_required); // show error                
                return false;
            }
            else{
                w('#account_name').hide();
                // Test Token and password
            //    if (w('input[name=token]').length >0 ){
            //       if (m.isEmpty(w('input[name=token]'))){
            //           return false;
            //       }else if(m.isEmpty(w('input[name=password]'))){
            //           return false;
            //       }
            //    }

            }
            return true;
			resizeIframe();
        });
        
        /** -------------------------------------------
         * 
         */
        w('#frm_changepass').submit(function( event ) {
            //event.preventDefault();
            
            var elemmsg = w('#error_message');
            elemmsg.addClass('error-text').hide();
            var pass = w('input[name=password]');
            var vpass=w('input[name=vpassword]');
            
			if (navigator.userAgent.search("Safari") >= 0 && navigator.userAgent.search("Chrome") < 0) {
				w(this).find('[placeholder]').each(function() {
					console.log(w(this).val() + " = " + w(this).attr("placeholder"));
					if (w(this).val() == w(this).attr("placeholder")) {
						w(this).val("");
					}
				});
			}
			
			var r=true;

            if (m.isEmtpy(pass) || (pass.val() == pass.attr("placeholder"))){
                pass.focus();
                r=false;
                pass.addClass('error');
                w('#error-password').show();
            }else{
                pass.removeClass('error');
                w('#error-password').hide();
            }
            
            if (m.isEmtpy(vpass) || (vpass.val() == vpass.attr("placeholder"))){
                vpass.focus();
				if(r==false){
                    pass.focus();
                }
                vpass.addClass('error');
                w('#error-vpassword').show();
                r=false;
            }else{
                w('#error-vpassword').hide();
            }

            if ((r===true) && (pass.val() !== vpass.val())){
                elemmsg.show().html(msgs.pass_notmatched);
                r=false;
                pass.focus();
            }

            if (!m.isValidPassword(pass)){
                w('.error_message').hide();
                elemmsg.show().html(msgs.pass_limit);
                r=false;
                pass.focus();
            }
        	console.log(r);
            
            return r;
        }); // frm_changepass submit

        /** ---------------------------------------
         * 
         * ---------------------------------------- */     
        w( "select[name=permission]" ).change(function () {
            var str = "";
            //w( "select option:selected" ).each(function() {
            //    str += w( this ).text() + " ";
            //});
            //w( "div" ).text( str );
            if (w(this).val()=="1"){ // Admin
                w("#dv-store_name").hide();
                w('input[name=store_name]').val("NaN").attr("disabled", "disabled");
            }else{
                w("#dv-store_name").show();
                w('input[name=store_name]').val("").attr("disabled", "disabled");
                w('input[name=store_name]').removeAttr("disabled");
            }
            
        })
        //.change()
        ;
        w('#frm_user').submit(function( event ) {
            var elem=null;
            var ret = true;
            var f_id_elem = w('input[name=id]');
            var isEdit = false;
            var error = w('#admin-error').hide();
            var $this = this;
//            for(var _field in fields_combo){
//                
//                elem = w('select[name='+fields[_field]+']');
//            }
            for(var _field in fields){
                elem = w('input[name='+fields[_field]+']');
               
                if ((fields[_field]==='password') && m.isEmtpyClassic(f_id_elem) && m.isEmtpyClassic(elem)){
                    // Only validate the password on new account.
                    elem.addClass('error-textfield');
                    ret=false;
                }else if (fields[_field]!=='password' && m.isEmtpyClassic(elem)){
                    console.log(_field+" "+fields[_field]+" is empty");
                    elem.addClass('error-textfield');
                    ret=false;
                }else if((fields[_field] === 'email') && !m.isValidEmail(elem.val())){
                    console.log(_field+" "+fields[_field]+" Invalid Email");
                    elem.addClass('error-textfield');
                    ret=false;
                }else{
                    elem.removeClass('error-textfield');
                }
            }
            
            var passelem = w('input[name=password]');
            if (!m.isValidPassword(passelem)){
                alert(msgs.pass_limit);
                ret=false;
            }
            
            if ((ret===true)&& m.isEmtpyClassic(f_id_elem)){
                event.preventDefault();
                // If if user exist
                w.ajax({
                    url: base_url+'/testuser'// m.urldecode(m.getCookie('t_burl'))
                    ,dataType:"json"
                    ,method:"POST"
                    ,data:w('#formedit input[name=account_name]')
                    //,contents:w('input[name=account_name]')
                    //,xhrFields: {withCredentials: true}
                })
                .done(function( data, textStatus, jqXHR ) {
                    // Check if suuscess
                    if (typeof data.stat === "undefined"){
                        //alert(data.name);
                        return false;
                    }else{
                        if (data.stat !== 0){
                            error.show().html(msgs.user_exist);
                            resizeIframe();
                            ret=false;
                        }else{
                            w($this).unbind('submit').submit();
                            return true;
                        }
                    }
                })
                .fail(function( jqXHR, textStatus, errorThrown ) {
                    error.show().html("Opss Something went wrong please try again.");
                    resizeIframe();
                    return false;
                });
            }else{
                resizeIframe();
                return ret;
            }

        });
        /** ===============================================================
         *          FORMs END
         * ================================================================== */

        

        /** ===============================================================
         *          Event Click Starts
         * ================================================================== */
        
        w(".gallery-filter a[href='#filter']").click(function(){
            console.log("Click .gallery-filter a[href='#filter']");
            //console.log("Click #gallery-filter-by-collapse");
            w(this).children("span").toggleClass("expand");
            w(".gallery-filter .filters").slideToggle("slow", function(){
                
            });
            return  false;
        });
        
        /**
         * 
         */
        
        w('.btn_unlockuser').click(function(){
            if (btnClick === true){
                //Do I need to give him a message.
                return;
            }
            btnClick=true;
            var $this = this;
            w.ajax({
                url: w($this).attr('href')
                ,dataType:"json"
                ,method:"POST"
                ,data:{'id':w($this).attr('data'),'s_id':w($this).attr('s_id')}
                //,data:w($this).attr('data')
            })
            .done(function( data, textStatus, jqXHR ) {
                btnClick=false;
                // Check if suuscess
                if (data.stat === 0){
                    alert(msgs.user_unlock);
                    w($this).hide();
                }else{
                    alert(data.msg);
                }
            })
            .fail(function( jqXHR, textStatus, errorThrown ) {
                btnClick=false;
                alert(msgs.server_error);
            });

        });
        /** -----------------------------------------------
         * 
         */
        w(".btn_edituser").click(function(){
            console.log("Edit the user");
            m.hideError();
            var selfdata = data["id"+w(this).attr('data')];
            
            w("input[name=id]").val(w(this).attr('data'));
            var k="";
            for(var _field in fields_combo){
                elem = w('#formedit select[name='+fields_combo[_field]+']');
                elem.val(selfdata[fields_combo[_field]]);
            }
            
            for (var key in fields) {
                k=fields[key];
                console.log("--> "+k+"-> "+selfdata[k]);
                if (selfdata.hasOwnProperty(k)) {
                  //w("input[name="+key+"]").attr("value",selfdata[key]); // Not reliable on second attempt
                    w("#formedit input[name="+k+"]").removeClass('error-textfield')
                        .val(selfdata[k]);
                }else{
                    w("#formedit  input[name="+k+"]").removeClass("error-textfield").val("");
                }
            }
            if (w(this).attr('role')==1){
                // Hide account name and store id
                w("#dv-store_name").hide();
            }else{
                w("#dv-store_name").show();
                w('input[name=store_name]').removeAttr("disabled");
            }
            w('#permission').hide();
            
            w('#formedit').fadeIn('slow',function(){
                resizeIframe();
                document.location="#user_form";
            });
            
            return null;
        });
        
        /** -------------------------------------------
         * 
         */
        w(".btn_deleteuser").click(function(){
            var selfdata = data["id"+w(this).attr('data')];
            //w("input[name=id]").attr("value",w(this).attr('data'));
            if (confirm("Are you sure to delete account name \""+data["id"+w(this).attr('data')].account_name+"\"")){
                document.location = m.urldecode(m.getCookie('t_burl'))+'admin/delete/'+w(this).attr('data');
            }
			resizeIframe();
            return null;
        });
        
        w("#btn_cancel").click(function(){
           w("#formedit").hide();
           w('input[name=id]').val(""); // reset not working, manualy clear data.
		   resizeIframe();
           return true;
        });
        
        w("#btn_add").click(function(){
            w("#frm_user")[0].reset();
            w("#dv-store_name").show();
            w("#formedit").show(function(){
                w('#permission').show();
                m.hideError();
                w('input[name=id]').val(""); // reset not working, manualy clear data.
                var elem=null;
                for(var _field in fields){
                    w('input[name='+fields[_field]+']')
                        .removeClass('error-textfield').val("");
                }
                resizeIframe();
            });
            
            return true;
        });
        
          
        w('#frm_resetpass').click(function(){

        });
        w('.ui-tabs-nav li').hover(function(){
            w(this).addClass('ui-state-hover');
        },function(){
            w(this).removeClass('ui-state-hover');
        });
        
		//m.fixedSafariPlaceholder();
        /*
         * Resize the parent frame
         */
        
        return m;
    };
   
   w(document).ready(function(){
        wAdmin = w(document).wAdmin();
        console.log("wDocument Ready");
    });
    
    // Working only on his page but not on iframe
    w(window).load(function(){
        // In this part.. I expect the wAdmin already define
        console.log("wWindow load");
        wAdmin.resizeFrame();
        
        if (typeof messages.success !== "undefined"){
            console.log(messages.success);
            alert(messages.success);
            
        }
        if (typeof messages.error !== "undefined"){
            console.log(messages.error);
            alert(messages.error);
        }

    });
}( jQuery ));
